package fr.inria.arles.temperatureManagement.communication;

import fr.inria.arles.temperatureManagement.exceptions.TemperatureManagerException;
import org.cybergarage.upnp.Action;
import org.cybergarage.upnp.Device;

import static fr.inria.arles.temperatureManagement.Constants.*;

/**
 * Provides communication with the Temperature Manager UPnP Device.
 * @author ajay chhatwal
 */
public class TemperatureManagerCommunicator {

    /**
     * Updates the current reference temperature setting at the
     * Temperature Manager UPnP Device.
     *
     * @param temp
     *            The reference temperature
     * @param tempManager
     *            The Temperature Manager UPnP device
     * @param partition
     *            The partition being referred to
     * @throws TemperatureManagerException
     *             if there is an error in performing the desired action at the
     *             Temperature Manager Device
     */
    public static void setTemp(Device tempManager,
            String partition, String temp)
            throws TemperatureManagerException {
        System.out.println("Connecting to Temperature Manager Device :- "
                + TEMPERATURE_MANAGER_DEVICE
                + " to set temperature setting");
        Action action =
                tempManager.getAction(SET_TEMP_ACTION);
        action.setArgumentValue(PARTITON_ARG, partition);
        action.setArgumentValue(TEMPERATURE_ARG, temp);

        if (!action.postControlAction()) {
            throw new TemperatureManagerException();
        }

    }

    /**
     * Gets the current actual temperature setting from the Temperature Manager
     * UPnP Device.
     *
     * @param tempManager
     *            The Temperature Manager UPnP device
     * @param partition
     *            The partition being referred to
     * @throws TemperatureManagerException
     *             if there is an error in performing the desired action at the
     *             Temperature Manager Device
     */
    public static String getTemp(Device tempManager, String partition)
            throws TemperatureManagerException {
        System.out.println("Connecting to Temperature Manager Device :- "
                + TEMPERATURE_MANAGER_DEVICE
                + " to get temperature setting");
        Action action =
                tempManager.getAction(GET_TEMP_ACTION);
        action.setArgumentValue(PARTITON_ARG, partition);

        if (action.postControlAction()) {
            return action.getArgument(TEMPERATURE_ARG).getValue();
        } else {
            throw new TemperatureManagerException();
        }

    }
}
